package net.dreamlu.api.oauth;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.dreamlu.api.util.OathConfig;
import net.dreamlu.api.util.TokenUtil;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.jfinal.ext.plugin.memcache.MCacheKit;
import com.jfinal.kit.StringKit;

/**
 * Oauth osc
 * @author L.cm
 * email: 596392912@qq.com
 * site:  http://www.dreamlu.net
 * @date Jun 24, 2013 9:58:25 PM
 */
public class OauthOsc extends Oauth {
    
    private static final Logger log = Logger.getLogger(OauthOsc.class);
    
    private static final String AUTH_URL = "http://www.oschina.net/action/oauth2/authorize"; // 授权
    private static final String TOKEN_URL = "http://www.oschina.net/action/openapi/token"; // tonken
    private static final String USER_INFO_URL = "http://www.oschina.net/action/openapi/user"; // 用户信息
    private static final String TWEET_PUB = "http://www.oschina.net/action/openapi/tweet_pub"; // 动弹
    
    private static final String ACCESS_TOKEN_OSC_ADMIN = "access_token_osc_admin"; // 用于缓存的key
    private static final long ACCESS_TOKEN_EXPIRY = 40000 * 1000; // token 超时时间, 43199，去除部分时间
    
    public OauthOsc() {
        super();
        setClientId(OathConfig.getValue("openid_osc"));
        setClientSecret(OathConfig.getValue("openkey_osc"));
        setRedirectUri(OathConfig.getValue("redirect_osc"));
    }
    
    /**
     * 获取授权url
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */ 
    public String getAuthorizeUrl() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("state", "osc");
        params.put("response_type", "code");
        params.put("client_id", getClientId());
        params.put("redirect_uri", getRedirectUri());
        return super.getAuthorizeUrl(AUTH_URL, params);
    }

    /**
     * 获取token
     * @param @param code
     * @param @return    设定文件
     * @return String    返回类型
     * @throws
     */
    public String getTokenByCode(String code) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        params.put("client_id", getClientId());
        params.put("client_secret", getClientSecret());
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", getRedirectUri());
        String token = TokenUtil.getAccessToken(super.doGet(TOKEN_URL, params));
        log.error(token);
        return token;
    }

    /**
     * 将管理员的token更新或者
     * ，从缓存中拿access_token，确保管理员一个月至少使用osc登录一次
     * @param code
     * @return
     */
    public String saveOrUpToken(String token) {
    	if (StringKit.notBlank(token)) {
    		MCacheKit.put(ACCESS_TOKEN_OSC_ADMIN, token, ACCESS_TOKEN_EXPIRY);
    		return token;
    	} else {
    		return MCacheKit.get(ACCESS_TOKEN_OSC_ADMIN);
    	}
    }
    
    /**
     *  获取用户信息
     * @param accessToken
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> getUserInfo(String accessToken) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", accessToken);
        // {id: 899**,email: "****@gmail.com",name: "彭博",gender: "male",avatar: "http://www.oschina.net/uploads/user/****",location: "广东 深圳",url: "http://home.oschina.net/****"}
		Map<String, Object> userinfo = JSON.parseObject(super.doGet(USER_INFO_URL, params), Map.class);
        log.error(userinfo);
        return userinfo;
    }
    
    /**
     * 发送文字动弹
     * @param accessToken
     * @param msg
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> tweetPub(String accessToken, String msg) {
    	Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", accessToken);
        params.put("msg", msg);
    	try {
    		Map<String, Object> dataMap = JSON.parseObject(super.doPost(TWEET_PUB, params), Map.class);
    		log.error(dataMap);
            return dataMap;
		} catch (Exception e) {
			log.error(e);
			return null;
		}
    }
    
    public static void main(String[] args) throws IOException {
    	OauthOsc osc = new OauthOsc();
    	System.out.println(osc.getAuthorizeUrl());

        // L0kOlo
//        String accessToken = osc.getTokenByCode("pffCru"); // 获取accessToken
//        System.out.println(osc.getUserInfo(accessToken));
        // {id=813039, email=596392912@qq.com, location=北京 海淀, name=孤独的3, gender=male, avatar=http://static.oschina.net/uploads/user/406/813039_50.jpg?t=1348824049000, url=http://my.oschina.net/qq596392912}
//      System.out.println(new OauthOsc().tweetPub(accessToken, "测试动弹，啦啦啦...").toString());
    }
}
